package com.ls.demo.tcp.handler;

import com.ls.demo.bean.Command;
import com.ls.demo.tcp.service.DispatcherCommand;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.java.Log;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 进行校验
 * @author liShan
 * @date 2019/8/30 14:55
 */
@Component
@ChannelHandler.Sharable
@Log
public class VerChannelHandlerImpl extends SimpleChannelInboundHandler<StringBuilder> {

    @Resource
    private DispatcherCommand dispatcherCommand;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, StringBuilder msg) {
        int idnex = 0;
        int increment = 2;
        String f5 = "F5";
        List<Command> commands = new ArrayList<>();
        while (msg.indexOf(f5) >= 0 && msg.indexOf(f5) <= msg.length()){
            String s = msg.substring(idnex, msg.indexOf(f5)+increment);
            msg.delete(idnex, msg.indexOf(f5)+increment);
            commands.add(Command.getCommand(s.trim()));
        }
        commands.forEach(m -> {
            String regex = "\\s";
            int min = 13;
            if ((!this.isCorrect(m)) || (m.getCommand().split(regex).length < min)){
                log.info(String.format("消息[%s]校验有误，被丢弃", m.getCommand()));
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
            }else {
                dispatcherCommand.uploadCommand(ctx, m);
            }
        });
    }

    /**
     * 对rcuCmdStr进行校验
     * @param rcuCmdStr rcuCmdStr对象
     * @return 返回校验结果
     */
    private boolean isCorrect(Command rcuCmdStr){
        return rcuCmdStr.getVer().equals(rcuCmdStr.getValCode())
                && rcuCmdStr.getLengthDec() == Integer.parseInt(rcuCmdStr.getLength(), 16)
                && rcuCmdStr.getDataLongDec() == Integer.parseInt(rcuCmdStr.getDataLong(), 16);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}
